package com.qfedu.service.impl;

import com.qfedu.dto.DeveloperDto;
import com.qfedu.mapper.DeveloperMapper;
import com.qfedu.model.Developer;
import com.qfedu.model.Project;
import com.qfedu.page.PageResult;
import com.qfedu.page.QueryPageBean;
import com.qfedu.service.IDeveloperService;
import com.qfedu.service.IProjectService;
import com.qfedu.utils.UUIDUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 概述:
 *
 * @Author: Tbh
 * @Date: 2022/6/27 20:22
 */

@Service
public class DeveloperServiceImpl implements IDeveloperService {

    @Autowired
    private DeveloperMapper developerMapper;

    @Autowired
    private IProjectService projectService;

    @Override
    public PageResult findPage(QueryPageBean queryPage) {

        PageResult result = new PageResult();

        // 当前页码
        Integer currentPage = queryPage.getCurrentPage();
        // 每页记录数
        Integer pageSize = queryPage.getPageSize();

        List<Developer> page = developerMapper.findPage((currentPage - 1) * pageSize, pageSize);

        Long count = developerMapper.count();

        result.setTotal(count);
        result.setRows(page);

        return result;
    }

    @Override
    @Transactional
    public int addAndBind(String dname, int[] pids) {
        Developer developer = new Developer();
        developer.setDid(UUIDUtils.uuid());
        developer.setDname(dname);
        developer.setUpdatetime(new Date());
        int row = developerMapper.add(developer);

        projectService.bindDid(developer.getDid(),pids);
        return row;
    }

    @Override
    public DeveloperDto findByDid(String did) {

        DeveloperDto developerDto = developerMapper.findByDidDto(did);

        List<Project> list = projectService.findByDid(did);
        int[] pids = null;
        if (ObjectUtils.isNotEmpty(list)) {
            pids = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                pids[i] = list.get(i).getPid();
            }
            developerDto.setPids(pids);
        }
        return developerDto;
    }

    @Override
    @Transactional
    public int updateAndBind(String did, String dname, int[] pids) {
        Developer developer = new Developer();
        developer.setDid(did);
        developer.setDname(dname);
        developer.setUpdatetime(new Date());
        int row = developerMapper.updateDev(developer);

        projectService.deleteDid(did);

        projectService.bindDid(did,pids);
        return row;
    }

    @Override
    @Transactional
    public int deleteByDid(String did) {
        int row = developerMapper.deleteByDid(did);
        projectService.deleteDid(did);
        return row;
    }
}
